package com.dces.jx.billtest.common.service;
import com.google.common.base.Strings;
import com.xdo.common.excel.ExcelExportUtil;
import com.xdo.common.util.DateUtils;
import com.xdo.domain.KeyValuePair;
import com.xdo.common.token.UserInfoToken;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.util.List;
/**
 * @author xdoV2.0
 * @date: 2021-9-2
 */
@Service
public class ExcelService {
    /***
     * 数据类型date
     */
    private static final String DATA_TYPE_DATE = "DATE";
    /***
     * 数据类型 Number
     */
    private static final String DATA_TYPE_NUMBER = "NUMBER";
    /***
     *
     * @param columnType
     * @param value
     * @return
     */
    private Object getColumnType(String columnType, String value) {
        if (Strings.isNullOrEmpty(value)) {
            return value;
        }
        switch (columnType) {
            case DATA_TYPE_DATE:
                return DateUtils.stringToSqlDate(value, "yyyy-MM-dd");
            case DATA_TYPE_NUMBER:
                try {
                    Number number = NumberUtils.createNumber(value);
                    return number;
                } catch (NumberFormatException e) {
                    return null;
                }
            default:
                return value;
        }
    }
    /**
     * 获取带Excel流的HttpHeader
     *
     * @param name
     * @param header
     * @param dtos
     * @return
     * @throws Exception
     */
    public <T> ResponseEntity getExcelHeaders(String name, List<KeyValuePair<String, String>> header, List<T> dtos, UserInfoToken userInfo) throws Exception {
        ByteArrayInputStream in = null;
        in = new ExcelExportUtil<T>().exportGeneric(name, header, dtos);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel;charset=ISO8859-1");
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="
                + new String(name.getBytes("UTF-8"), "ISO8859-1") + ".xlsx");
        return ResponseEntity
                .ok()
                .headers(headers)
                .body(new InputStreamResource(in));
    }
}
